#import "MonitorDBManager.h"
#import <fmdb/FMDB.h>
#import <sqlite3.h>
#import "ALUtils.h"
#import "MonitorDBModel.h"
@implementation MonitorDBManager{
    FMDatabase* db;
    NSString* tableName;
}
+ (MonitorDBManager *)shareInstance {
    static MonitorDBManager *singleton;
    if (!singleton) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            singleton = [MonitorDBManager new];
        });
    }
    return singleton;
}

-(instancetype)init{
    if (self = [super init]) {
        tableName=@"t_goal_record";
        NSString *dbPath = [NSString stringWithFormat:@"%@/goal.db",APP_CACHE_DIR];
        ALLOGT(dbPath);
        db = [FMDatabase databaseWithPath:dbPath];
        
        if(![db isOpen]&&[db open]){
            //设置DB的time格式
            NSDateFormatter *fmt = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:8*60*60];
            [fmt setTimeZone:timeZone];
            [db setDateFormat:fmt];
            ALLOG(@"success");
            [self createTable];
            ALLOGT([db lastError]);
        }else{
            ALLOG(@"db open error");
        }
    }
    return self;
}


-(BOOL)createTable{
    NSString * sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ ( _id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT, app_version TEXT, timestamp INTEGER);",tableName ];
    return [db executeUpdate:sql];
}

- (NSArray<MonitorDBModel *> *)searchDataWithDomain:(NSString *)domain deleteData:(BOOL)deleteData {
    NSMutableArray *result = [NSMutableArray array];;
    NSString * sqlQuery = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY _id ASC",tableName];
    FMResultSet *rs = [db executeQuery:sqlQuery];
    while ([rs next]) {
        MonitorDBModel* model = [MonitorDBModel new];
        model.index = [rs intForColumn:@"_id"];
        model.record = [rs stringForColumn:@"data"];
        [result addObject:model];
    }
    [rs close];
    
    return result;
}

/**
 * 搜索出指定域下特定条数的数据
 * @param domain 指定的域
 * @param deleteData 查出之后删除数据
 * @param count 最多查出多少条数据
 */
- (NSArray<MonitorDBModel *> *)searchDataWithDomain:(NSString *)domain deleteData:(BOOL)deleteData count:(NSInteger)count {
    NSMutableArray *result = [NSMutableArray array];;
    NSString * sqlQuery = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY _id ASC LIMIT %ld",tableName,count];
    FMResultSet *rs = [db executeQuery:sqlQuery];
    while ([rs next]) {
        MonitorDBModel* model = [MonitorDBModel new];
        model.index = [rs intForColumn:@"_id"];
        model.record = [rs stringForColumn:@"data"];
        [result addObject:model];
    }
    [rs close];
    
    return result;
}



- (int64_t)insertData:(NSString *)data {
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO %@ (data,app_version,timestamp) VALUES(?,?,?);",tableName];
    NSString *data_str = data?:@"";
    NSString *app_version = @"";
    NSTimeInterval curTime = [[NSDate date] timeIntervalSince1970];
    unsigned int curTime_unint = (unsigned int)(curTime);
    BOOL success = [db executeUpdate:insertSQL ,data_str, app_version,@(curTime_unint)];
    if(success){
        return [db lastInsertRowId];
    }else{
        return -1;
    }
}




/**
 * 删除所有数据
 */
- (BOOL)clearData {
    NSString * sqlQuery = [NSString stringWithFormat:@"DELETE FROM %@",tableName];
    BOOL success = [db executeUpdate:sqlQuery];
    return success;
}

/**
 * 删除特定条数的数据
 */
-(BOOL)clearDataFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    NSString * sqlQuery = [NSString stringWithFormat:@"DELETE FROM %@ WHERE _id <= %ld and _id >= %ld",tableName,toIndex,fromIndex];
    BOOL success = [db executeUpdate:sqlQuery];
    return success;
}

//-(BOOL)createRow:(RNDBModuleInfoDTO*)dto{
//    return [db executeUpdate:@"insert into t_rn_module_info(name, version, min_version,update_time,status,is_full) values (?, ?, ?, ?, ?, ?)" ,
//            dto.name, dto.version,@(dto.minVersion),[NSDate date],@(dto.status),@(dto.isFull)];
//}
//
//
//-(RNDBModuleInfoDTO*)selectRow:(RNDBModuleInfoDTO*)dto{
//    FMResultSet *rs = [db executeQuery:@"select * from t_rn_module_info where name = ? and version =? and min_version =?",dto.name,dto.version,@(dto.minVersion)];
//    RNDBModuleInfoDTO* _dto;
//    if ([rs next]) {
//        _dto  = [[RNDBModuleInfoDTO alloc]init];
//        _dto.name = dto.name;
//        _dto.version = dto.version;
//        _dto.minVersion = dto.minVersion;
//        _dto.status = [rs intForColumn:@"status"];
//        _dto.isFull = [rs intForColumn:@"is_full"];
//    }
//    return _dto;
//}
//-(RNDBModuleInfoDTO*)selectLatestRow:(NSString*)name{
//    FMResultSet *rs = [db executeQuery:@"select * from t_rn_module_info where name = ? and status > 0 order by version desc,min_version desc limit 0,1",name];
//    RNDBModuleInfoDTO* _dto;
//    if ([rs next]) {
//        _dto  = [[RNDBModuleInfoDTO alloc]init];
//        _dto.name = name;
//        _dto.version = [rs stringForColumn:@"version"];
//        _dto.minVersion = [rs intForColumn:@"min_version"];
//        _dto.status = [rs intForColumn:@"status"];
//        _dto.isFull = [rs intForColumn:@"is_full"];
//        _dto.fileHash = [rs stringForColumn:@"file_hash"];
//    }
//    return _dto;
//}
//
//
//-(NSInteger)isModuleExist:(RNDBModuleInfoDTO*)dto{
//    FMResultSet *rs = [db executeQuery:@"select count(*) as ct from t_rn_module_info where name = ? and version =? and min_version =?",dto.name,dto.version,@(dto.minVersion)];
//    NSInteger count = 0;
//    if ([rs next]) {
//        count = [rs intForColumn:@"ct"];
//    }
//    [rs close];
//    return count;
//}
//
//
//-(BOOL)updateSuccessByModel:(RNModuleInfoModel*)model{
//    return [db executeUpdate:@"update t_rn_module_info set status = ?,update_time=?,file_hash=? where name = ? and version =? and min_version =?" ,@"1", [NSDate date],model.fileHash,model.name,model.version,@(model.minVersion)];
//}
//
//
//
//
//-(BOOL)updateRow:(RNDBModuleInfoDTO*)dto{
//    return [db executeUpdate:@"update t_rn_module_info set status = ?,update_time=? where name = ? and version =? and min_version =?" ,@(dto.status), [NSDate date],dto.name,dto.version,@(dto.minVersion)];
//}

// db无需经常关闭，除非你更换schema
-(void)closeDB{
    [db close];
}


@end
